<template>
    <div>
        <!--搜索-->
        <div id="searchData">
            <el-form :inline="true" :model="searchForm" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="searchForm.productName" placeholder="——请输入商品名称——"
                              class="center-text"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="search" icon="el-icon-search">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addProductImage" icon="el-icon-circle-plus-outline">添加</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="refresh" icon="el-icon-refresh">刷新</el-button>
                </el-form-item>
            </el-form>

        </div>

        <!-- table -->
        <el-table
                :data="tableData"
                style="width: 100%"
        >
            <!-- 序号 -->
            <el-table-column
                    type="index"
                    :index="indexMethod"
            >
            </el-table-column>
            <el-table-column
                    prop="product.productName"
                    label="商品名称"
                    width="120"
            >
            </el-table-column>
            <el-table-column
                    prop="imageName"
                    label="图片名称"
                    width="120"
            >
            </el-table-column>
            <el-table-column
                    prop="imageurl"
                    label="图片路径"
                    width="120"
            >
                <template slot-scope="scope">
                    <el-image
                            style="width: 60px; height: 40px"
                            :src="scope.row.imageurl"
                    ></el-image>
                </template>
            </el-table-column>
            <el-table-column
                    prop="userName"
                    label="创建人"
                    width="120"
                    :formatter="createFormatter"
            >
            </el-table-column>
            <el-table-column
                    prop="createtime"
                    label="创建时间"
                    width="160"
            >
            </el-table-column>
            <el-table-column
                    prop="description"
                    label="图片描述"
                    width="120"
            >
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
                <template slot-scope="scope">
                    <el-button size="small" type="primary" icon="el-icon-edit-outline"
                               @click="updataProductImage(scope.row)">编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteproductImage(scope.row.id)"
                               icon="el-icon-remove-outline">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页功能-->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="searchForm.currentPage"
                :page-sizes="[1,2,5,10]"
                :page-size="searchForm.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>


        <!--添加或者更新的form表单-->
        <el-dialog
                :visible.sync="dialogFormVisible"
                :before-close="handleClose"
        >
            <el-form
                    ref="addEditform"
                    :rules="rules"
                    :model="addEditform"
            >
                <el-form-item label="请选择商品" :label-width="formLabelWidth" prop="productId">
                    <div class="left">
                        <el-select
                                v-model="addEditform.productId"
                                clearable
                                placeholder="请选择商品"
                                style="width: 100%"
                        >
                            <el-option
                                    v-for="item in optionsProduct"
                                    :label="item.productName"
                                    :value="item.productId"
                            >
                            </el-option>
                        </el-select>
                    </div>
                </el-form-item>
                <el-form-item
                        label="图片名称"
                        :label-width="formLabelWidth"
                        prop="imageName"
                >
                    <el-input
                            v-model="addEditform.imageName"
                            autocomplete="off"
                            placeholder="图片名称"
                    ></el-input>
                </el-form-item>
                <el-form-item label="商品封面图片" :label-width="formLabelWidth" prop="imageurl">
                    <el-upload
                            class="avatar-uploader"
                            :action="uploadAction"
                            :headers="head"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="addEditform.imageurl" :src="addEditform.imageurl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>

                <el-form-item
                        label="图片描述"
                        :label-width="formLabelWidth"
                >
                    <el-input
                            v-model="addEditform.description"
                            autocomplete="off"
                            placeholder="图片描述"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="enterAdd" v-if="actor=='add'">确定添加</el-button>
            <el-button type="primary" @click="enterEdit" v-if="actor=='edit'">确定编辑</el-button>
        </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "ProductImage",
        data() {
            return {
                searchForm: {
                    currentPage: 1, //当前页数
                    pageSize: 5,//每页的数量
                    //用来接收前端后端查出来的数据
                    productName: "",
                },
                total: 0, //总options条数
                tableData: [],
                //加载更新人（不能用undefined）报错；
                Options: [],
                optionsProduct: [],
                dialogFormVisible: false,
                formLabelWidth: "120px",

                addEditform: {
                    imageName: '',
                    productId: '',
                    description: '',
                    imageurl: '',
                },
                actor: '',
                //图片参数
                head: '',
                //上传图片访问路径
                uploadAction: this.$http.getUri() + "/product/list/uploadFile",

                rules: {
                    //imageurl: [{required: true, message: '图片不能为空', trigger: 'change'}],
                    productId: [{required: true, message: '商品不能为空', trigger: 'change'}],
                    imageName: [{required: true, message: '图片名称不能为空', trigger: 'change'}],
                }
            }
        },
        created() {
            this.selectData();
            this.loadUpdateBy();
            this.loadProductMsg();
            this.head = {
                token: sessionStorage.getItem("token")
            }
        },
        methods: {

            //刷新方法
            refresh() {
                // location.reload();
                this.searchForm = {};
                this.searchForm.productName = "";
                this.searchForm.currentPage = 1;
                this.searchForm.pageSize = 5;
                this.selectData();

            },
            //分页查询所有信息
            selectData() {
                this.$http.post("/product/image/select", this.searchForm).then(result => {

                    this.tableData = result.data.data.records;
                    this.total = result.data.data.total;
                })
            },

            //添加按钮的方法
            addProductImage() {
                this.actor = "add";
                this.dialogFormVisible = true;
            },

            //确认添加方法
            enterAdd() {
                this.$refs.addEditform.validate((valid) => {
                    console.log(valid);
                    if (valid) {
                        this.actor = ''
                        this.$http.post("/product/image/insertProductImage", this.addEditform).then(resp => {
                            //console.log("777777777777resprespresp", resp)
                            if (resp.data.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '添加成功!'
                                });
                                this.selectData();
                            }
                        })
                        this.addEditform = {}
                        this.dialogFormVisible = false;
                    }
                });
            },
            handleClose() {
                this.dialogFormVisible = false;
                this.addEditform = {};
                this.actor = null;
            },

            //编辑按钮
            updataProductImage(row) {
                this.actor = "edit"
                this.dialogFormVisible = true;
                this.addEditform.id = row.id
                this.addEditform = row;
            },
            //确认编辑方法
            enterEdit() {
                this.$refs.addEditform.validate((valid) => {
                    //console.log(valid);
                    if (valid) {
                        this.actor = "";
                        this.$http.post("/product/image/updateProductImage", this.addEditform).then(resp => {
                            if (resp.data.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '更新成功!'
                                });
                                this.selectData();
                            }
                        })
                        this.addEditform = {}
                        this.dialogFormVisible = false;
                    }
                })
            },


            //加载商品信息（用于添加按钮遍历下拉框）
            loadProductMsg() {
                this.$http.get("/product/list/selectAll").then(resp => {
                    this.optionsProduct = resp.data.data;
                    // 另一种方式（前端获取）
                    // for (let i = 0; i < this.tableData.length; i++) {
                    //     for (let j = 0; j < this.optionsProduct.length; j++) {
                    //         if(this.tableData[i].productId===this.optionsProduct[j].productId){
                    //             this.tableData[i].productName=this.optionsProduct[j].productName;
                    //         }
                    //     }
                    // }
                    // console.log(")))))))))",this.tabledata)
                },errorMsg => {
                    console.log("加载商品信息失败")
                })
            },
            //获取所有的用户信息,创建人
            loadUpdateBy() {
                this.$http.get("/system/user/selectAll").then(result => {
                    this.Options = result.data.data;
                })
            },
            //从查到的用户信息中查询对应的创建者姓名
            createFormatter(row) {
                for (let i = 0; i < this.Options.length; i++) {
                    if (row.creator === this.Options[i].userId) {
                        return this.Options[i].userName;
                    }
                }
            },

            // //删除数据
            deleteproductImage(id) {
                this.$confirm('是否删除该数据？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.get("/product/image/deleteProductImageById?id=" + id).then(resp => {
                        if (resp.data.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.searchForm.currentPage = 1;
                            this.selectData();
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },


            //每页数量发生变化
            handleSizeChange(val) {
                this.searchForm.pageSize = val;
                this.selectData();
            },
            //页码发生变化
            handleCurrentChange(val) {
                this.searchForm.currentPage = val;
                this.selectData();
            },
          //显示索引
          indexMethod(index) {
            return index + 1;
          },
            //搜索
            search() {
                this.selectData();
            },

            //图片上传的方法
            handleAvatarSuccess(res, file) {
                this.addEditform.imageurl = res.data
            },
            beforeAvatarUpload(file) {
                const isImage = file.type.startsWith('image/');
                const isJPGorPNG = isImage && (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/webp');
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isJPGorPNG) {
                    this.$message.error('上传头像图片只能是 JPG或者是PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPGorPNG && isLt2M;
            },
        }
    }
</script>

<style scoped>
    /*上传图片的样式*/
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        align-items: center;
        border-color: #409EFF;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 100px;
        padding-top: 78px;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .left {
        /* 设置弹出框中输入框的宽度和位置 */
        width: 450px;
        text-align: left;
    }
</style>